package org.lex.dbq.model.export;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public abstract class AbstractExporter extends Exporter {

	public abstract void exportHeader(ResultSet rs, PrintWriter out) throws IOException, SQLException;

	public abstract void exportRow(Object[] row, PrintWriter out) throws IOException, SQLException;

	public abstract void exportFooter(ResultSet rs, PrintWriter out) throws IOException, SQLException;

	@Override
	public void export(ResultSet rs, Writer out) throws IOException, SQLException {
		PrintWriter pw = new PrintWriter(out);

		log.info("export header");
		this.exportHeader(rs, pw);
		log.info("export rows");
		ResultSetMetaData meta = rs.getMetaData();
		int columnCount = meta.getColumnCount();
		int rowCount = 0;
		Object[] row = new Object[columnCount];
		while (rs.next()) {
			for (int i = 0; i < columnCount; i++) {
				row[i] = rs.getObject(i + 1);
			}
			this.exportRow(row, pw);
			rowCount++;
		}
		log.info(rowCount + " rows found");
		log.info("export footer");
		this.exportFooter(rs, pw);
		pw.flush();
		pw.close();
		rs.close();
	}
}
